<template>
  <div class="container" ref="mainCon">
    <topTitle :titleText="titleText" :titleExplain="titleExplain"></topTitle>
    <div class="mainCon">
      <el-row class="toolbar searchInputWidth" style="padding-bottom: 0">
        <el-form :inline="true" :model="filterField" ref="searchConditions">
          <el-col :lg="8" :xl="6">
            <el-form-item label="区域" class="row-padding-bottom">
              <el-cascader
                ref="manageArea"
                v-model="areaId"
                :options="areasOptions"
                @change="getAreaId"
                clearable
                filterable
                :props="{ checkStrictly: true }"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :xl="6">
            <el-form-item label="申请状态" class="row-padding-bottom">
              <el-select
                v-model="filterField.status"
                filterable
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="item in statusOptions"
                  :key="item.id"
                  :label="item.text"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <template v-if="advanced">
            <el-col :lg="8" :xl="6">
              <el-form-item label="申请日期" class="row-padding-bottom">
                <timeSelection
                  @getStartTimeValue="getStartTimeValue"
                  @getEndTimeValue="getEndTimeValue"
                  :startTime="startTime"
                  :endTime="endTime"
                ></timeSelection>
              </el-form-item>
            </el-col>
          </template>
          <el-form-item label="">
            <a
              @click="toggleAdvanced"
              style="margin-left: 40px; color: #409eff; cursor: pointer"
              class="btnColor"
            >
              {{ advanced ? '收起' : '展开' }}
              <i
                :class="advanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
              ></i>
            </a>
            <el-button
              type="primary"
              icon="icon iconfont iconchazhao1"
              @click="searchList"
              class="searchBtn"
            >
              <span>搜索</span>
            </el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <div class="spacing"></div>
      <div
        ref="tableBox"
        :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
      >
        <el-table
          ref="tableBox1"
          @sort-change="sortChange"
          :max-height="tableHeight"
          :data="tableList"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          highlight-current-row
          v-loading="loading"
          stripe
          style="border: 1px solid #dfe6ec"
        >
          <el-table-column
            prop="areaName"
            label="所在区域"
            align="center"
            min-width="120"
            :formatter="formatTd"
          ></el-table-column>
          <el-table-column
            prop="operator"
            label="经办人"
            align="center"
            min-width="120"
            :formatter="formatTd"
          ></el-table-column>
          <el-table-column
            prop="operatorTel"
            label="手机号码"
            align="center"
            min-width="120"
            :formatter="formatTd"
          ></el-table-column>
          <el-table-column
            label="项目施工合同"
            align="center"
            width="120"
            :formatter="formatTd"
          >
            <template slot-scope="scope">
              <el-link
                v-hasBtn="'projectChecks:detail'"
                @click="getUploadFile(scope.row.id)"
                type="primary"
              >
                查看
              </el-link>
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="申报时间"
            sortable="custom"
            align="center"
            width="180"
            :formatter="formatTd"
          ></el-table-column>
          <el-table-column
            prop="statusDesc"
            label="状态"
            align="center"
            min-width="120"
            :formatter="formatTd"
          ></el-table-column>
          <el-table-column
            prop="reason"
            label="驳回原因"
            align="center"
            :formatter="formatTd"
          >
            <template slot-scope="scope">
              <el-tooltip
                v-if="scope.row.reason && scope.row.reason.length > 20"
                content="Right center"
                placement="right"
                effect="light"
              >
                <div slot="content" style="width: 400px; line-height: 26px">
                  {{ scope.row.reason }}
                </div>
                <span>{{ scope.row.reason.substring(0, 20) }}</span>
              </el-tooltip>
              <span v-else>{{ scope.row.reason }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" align="left" fixed="right">
            <template slot-scope="scope">
              <template
                v-if="
                  scope.row.status === 'WAIT_ALLOCATION' &&
                  $store.state.userType === 'MONITOR'
                "
              >
                <el-link
                  v-hasBtn="'projectChecks:update'"
                  @click="showDialog('formData', scope.row.id)"
                  type="primary"
                >
                  分配行业
                </el-link>
                <el-link
                  v-hasBtn="'projectChecks:update'"
                  @click="showDialog('refuse', scope.row.id)"
                  type="primary"
                >
                  驳回
                </el-link>
              </template>
              <template v-else-if="scope.row.status === 'WAIT_AUDIT'">
                <el-link
                  v-hasBtn="'projectChecks:update'"
                  @click="approved(scope.row)"
                  type="primary"
                >
                  审核通过
                </el-link>
                <el-link
                  v-hasBtn="'projectChecks:update'"
                  @click="showDialog('refuse', scope.row.id)"
                  type="primary"
                >
                  驳回
                </el-link>
              </template>
              <template v-else>
                <span>--</span>
              </template>
            </template>
          </el-table-column>
          <!-- 表格数据为空时，页面显示 -->
          <div slot="empty" v-show="isShow">
            <emptyTable emptyText="暂无相关信息"></emptyTable>
          </div>
        </el-table>
        <Pagination
          ref="pagination"
          @getList="getTableList"
          :filterField="filterField"
          :requestUrl="requestUrl"
          @getpageNo="getpageNo"
          @getpageSize="getpageSize"
        ></Pagination>
      </div>
    </div>
    <!-- 分配行业 -->
    <el-dialog
      title="分配行业"
      :visible.sync="manyUpdateDia"
      @close="closeDialog('formData')"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      width="420px"
      class="tipDialog"
    >
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formData"
        label-width="120px"
      >
        <el-form-item label="行业" prop="industryId">
          <el-select
            v-model="formData.industryId"
            filterable
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in industryOptions"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div div slot="footer" class="dialog-footer">
        <el-button @click.native="closeDialog('formData')" class="cancel"
          >取消</el-button
        >
        <el-button
          type="primary"
          @click.native="submitIndustry('formData')"
          v-sdc
          :loading="isSaveLoading"
          class="save"
          >保存</el-button
        >
      </div>
    </el-dialog>
    <!-- 驳回 -->
    <el-dialog
      title="审核驳回"
      :visible.sync="refuseStatus"
      @close="closeDialog('refuse')"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      width="420px"
      class="tipDialog"
    >
      <el-form
        :model="refuse"
        :rules="refuseRules"
        ref="refuse"
        label-width="120px"
      >
        <el-form-item label="驳回原因" prop="reason">
          <el-input
            v-model="refuse.reason"
            type="textarea"
            :rows="3"
            maxlength="300"
            show-word-limit
            placeholder="请输入驳回原因"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <div div slot="footer" class="dialog-footer">
        <el-button @click.native="closeDialog('refuse')" class="cancel"
          >取消</el-button
        >
        <el-button
          type="primary"
          @click.native="submitRefuse('refuse')"
          v-sdc
          :loading="isSaveLoading"
          class="save"
          >保存</el-button
        >
      </div>
    </el-dialog>
    <!-- 合同附件 -->
    <contractEnclosureDialog
      v-if="uploadContract"
      dialogTitle="施工合同"
      :tableData="fileBackList"
      @closeDialog="hiddenDialog"
    ></contractEnclosureDialog>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import scrollTable from '@/mixin/scrollTable.js'

export default {
  name: 'projectChecks',
  mixins: [scrollTable],
  data() {
    return {
      titleText: '项目审核',
      titleExplain:
        '施工方通过“一码办事”功能申请项目建档，由监察部门分配行业，由行业主管完善项目信息并建档',
      statusOptions: [],
      tableList: [],
      requestUrl: 'api-p/qrprojectapplication/expand/list',
      areaId: '', //区域
      //搜索条件
      filterField: {
        areaId: '', //区域
        status: '', //开工状态  ；默认只显示已开工状态的项目2020/10/19 恩施
        startDateStr: '',
        endDateStr: '',
      },
      pageSize: 20,
      pageNo: 1,
      startTime: '',
      endTime: '',
      uploadContract: false, //合同附件
      fileBackList: [],
      manyUpdateDia: false, //分配行业
      formData: {
        id: '',
        industryId: '',
      },
      formRules: {
        industryId: [
          {
            required: true,
            message: '请选择行业',
            trigger: 'change',
          },
        ],
      },
      isSaveLoading: false,
      refuseStatus: false, //驳回
      refuse: {
        id: '',
        reason: '',
        people: '',
      },
      refuseRules: {
        reason: [
          {
            required: true,
            message: '请输入驳回原因',
            trigger: 'blur',
          },
        ],
        people: [
          {
            required: true,
            message: '请输入处理人',
            trigger: 'blur',
          },
        ],
      },
      refuseLoading: false,
      loading: false,
      isShow: false,
      advanced: false,
    }
  },
  computed: {
    ...mapState(['areasOptions', 'industryOptions']),
  },
  async mounted() {
    await this.getApplyStatus()
    this.$nextTick(() => {
      this.$refs.pagination.getTableListData(this.pageNo, this.pageSize)
    })
  },
  activated() {
    this.$nextTick(() => {
      this.$refs.pagination.getTableListData(this.pageNo, this.pageSize)
    })
  },
  created() {
    this.filterField.startDateStr = this.$route.query.createTime
    this.filterField.status = this.$route.query.status
    this.filterField.areaId = this.$route.query.areaId
    this.filterField.startDateStr = this.$route.query.createTime
    this.filterField.endDateStr = this.$route.query.createTime

    this.startTime = this.$route.query.createTime
    this.endTime = this.$route.query.createTime
    this.areaId = this.$route.query.areaId
  },
  methods: {
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    getpageSize(val) {
      this.pageSize = val
    },
    getpageNo(val) {
      this.pageNo = val
    },
    // 申请状态
    getApplyStatus() {
      return this.axios({
        method: 'post',
        url: 'api-p/qrprojectapplication/expand/findstatus',
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.statusOptions = response.data.result
          } else {
            this.$message.error(response.data.errorMsg)
          }
        })
        .catch((error) => {
          if (error.response) {
            this.$message.error(error.response.data)
          }
        })
    },
    // 合同附件
    getUploadFile(id) {
      // 获取附件查询图片
      var data = {
        associatedName: 'T_CS_QR_PROJECT_APPLICATION',
        associatedId: id,
      }
      this.axios({
        method: 'post',
        url: 'api-f/files/list',
        data: data,
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.fileBackList = response.data.result
            this.uploadContract = true
          } else {
            this.$message.error(res.data.errorMsg)
          }
        })
        .catch((error) => {})
    },
    hiddenDialog() {
      this.uploadContract = false
    },
    // 列表
    getTableList(data) {
      this.tableList = data
      this.loading = false
      if (this.tableList.length < 1) {
        this.isShow = true
      }
    },
    searchList() {
      this.$refs.pagination.getTableListData()
    },
    //获取选中的区域最后一级id
    getAreaId() {
      var areaId = this.areaId[this.areaId.length - 1]
      this.filterField.areaId = areaId
    },
    getStartTimeValue(val) {
      if (val) {
        this.filterField.startDateStr = val
        this.startTime = val
      } else {
        this.filterField.startDateStr = ''
        this.startTime = ''
      }
    },
    getEndTimeValue(val) {
      if (val) {
        this.filterField.endDateStr = val
        this.endTime = val
      } else {
        this.filterField.endDateStr = ''
        this.endTime = ''
      }
    },
    //分配行业
    showDialog(ele, id) {
      if (ele == 'formData') {
        this.manyUpdateDia = true
        this.formData.id = id
      } else {
        this.refuseStatus = true
        this.refuse.id = id
      }
    },
    submitIndustry(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.isSaveLoading = true
          let findOne = this.industryOptions.find(
            (v) => v.code === this.formData.industryId
          )
          let industryName = findOne && findOne.name
          this.axios({
            method: 'post',
            url: 'api-p/qrprojectapplication/expand/editindustry',
            data: {
              id: this.formData.id,
              industryId: this.formData.industryId,
              industryName,
            },
          })
            .then((response) => {
              if (response.data.hasError) {
                this.$message.error(response.data.errorMsg)
              } else {
                this.$message.success('操作成功')
                this.manyUpdateDia = false
                this.$refs.pagination.getTableListData(
                  this.pageNo,
                  this.pageSize
                )
              }
              this.isSaveLoading = false
            })
            .catch((error) => {
              if (error.response) {
                this.$message.error(error.response.data)
              }
              this.isSaveLoading = false
            })
        } else {
          return false
        }
      })
    },
    //驳回
    submitRefuse(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.isSaveLoading = true
          let data = {
            id: this.refuse.id,
            reason: this.refuse.reason,
          }
          this.axios({
            method: 'post',
            url: 'api-p/qrprojectapplication/expand/refuse',
            data,
          })
            .then((response) => {
              if (response.data.hasError) {
                this.$message.error(response.data.errorMsg)
              } else {
                this.$message.success('操作成功')
                this.refuseStatus = false
                this.$refs.pagination.getTableListData(
                  this.pageNo,
                  this.pageSize
                )
              }
              this.isSaveLoading = false
            })
            .catch((error) => {
              if (error.response) {
                this.$message.error(error.response.data)
              }
              this.isSaveLoading = false
            })
        } else {
          return false
        }
      })
    },
    closeDialog(ele) {
      this.$refs[ele].resetFields()
      if (ele == 'formData') {
        this.manyUpdateDia = false
      } else {
        this.refuseStatus = false
      }
    },
    approved({ areaId, industryId, id } = row) {
      this.$router.push({
        path: '/home/oneCode/updateProjectInfo',
        name: 'updateProjectInfo',
        query: {
          areaId,
          industryId,
          id,
        },
      })
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/oneCode/projectChecks',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
  },
}
</script>
<style lang="less" scoped>
.mainCon {
  top: 210px;
}
</style>
